import React, { memo, useCallback, useState, useEffect } from 'react';
import { Input, Select, Button, Space, Card, Row, Col, Collapse, Tag } from 'antd';
import { SearchOutlined, FilterOutlined, ClearOutlined, DownOutlined } from '@ant-design/icons';
import type { ICourseSearchProps } from '@/types/components/course';
import { CourseStatusEnum } from '@/types/course';
import { useDebounce } from '@/hooks';
import styles from './CourseSearch.module.css';

const { Option } = Select;
const { Panel } = Collapse;

/**
 * 课程搜索组件
 * @description 用于搜索和筛选课程，支持关键词搜索和高级筛选
 */
const CourseSearch: React.FC<ICourseSearchProps> = memo(({
  keyword = '',
  onSearch,
  filters = {},
  onFilterChange,
  onReset,
  categories,
  className,
  placeholder = '搜索课程名称、课程代码、教师',
  showAdvancedFilter = true
}) => {
  const [searchKeyword, setSearchKeyword] = useState(keyword);
  const [localFilters, setLocalFilters] = useState(filters);
  const [showAdvanced, setShowAdvanced] = useState(false);

  // 防抖搜索
  const debouncedKeyword = useDebounce(searchKeyword, 300);

  // 搜索关键词变化时触发搜索
  useEffect(() => {
    if (debouncedKeyword !== keyword) {
      onSearch(debouncedKeyword);
    }
  }, [debouncedKeyword, keyword, onSearch]);

  // 处理搜索输入
  const handleSearchChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
    setSearchKeyword(e.target.value);
  }, []);

  // 处理搜索按钮点击
  const handleSearchClick = useCallback(() => {
    onSearch(searchKeyword);
  }, [searchKeyword, onSearch]);

  // 处理筛选条件变化
  const handleFilterChange = useCallback((key: string, value: any) => {
    const newFilters = { ...localFilters, [key]: value };
    setLocalFilters(newFilters);
    onFilterChange?.(newFilters);
  }, [localFilters, onFilterChange]);

  // 处理重置
  const handleReset = useCallback(() => {
    setSearchKeyword('');
    setLocalFilters({});
    onReset?.();
  }, [onReset]);

  // 处理高级筛选展开/收起
  const handleAdvancedToggle = useCallback(() => {
    setShowAdvanced(!showAdvanced);
  }, [showAdvanced]);

  // 检查是否有筛选条件
  const hasFilters = Object.values(localFilters).some(value => 
    value !== undefined && value !== '' && 
    (!Array.isArray(value) || value.length > 0)
  );
  const hasSearch = searchKeyword.trim() !== '';

  // 获取选中的分类名称
  const getSelectedCategoryNames = () => {
    if (!localFilters.categoryIds || localFilters.categoryIds.length === 0) return [];
    return categories
      .filter(category => localFilters.categoryIds!.includes(category.id))
      .map(category => category.name);
  };

  return (
    <div className={`${styles.courseSearch} ${className || ''}`}>
      {/* 基础搜索区域 */}
      <Card className={styles.searchCard} size="small">
        <div className={styles.searchRow}>
          <div className={styles.searchInput}>
            <Input
              value={searchKeyword}
              onChange={handleSearchChange}
              placeholder={placeholder}
              prefix={<SearchOutlined />}
              suffix={
                searchKeyword && (
                  <Button
                    type="text"
                    size="small"
                    icon={<ClearOutlined />}
                    onClick={() => setSearchKeyword('')}
                  />
                )
              }
              onPressEnter={handleSearchClick}
              allowClear
            />
          </div>
          
          <Space>
            <Button
              type="primary"
              icon={<SearchOutlined />}
              onClick={handleSearchClick}
            >
              搜索
            </Button>
            
            {showAdvancedFilter && (
              <Button
                type={showAdvanced ? 'primary' : 'default'}
                icon={<FilterOutlined />}
                onClick={handleAdvancedToggle}
              >
                高级筛选
                <DownOutlined 
                  className={`${styles.expandIcon} ${showAdvanced ? styles.expanded : ''}`} 
                />
              </Button>
            )}
            
            {(hasFilters || hasSearch) && (
              <Button
                icon={<ClearOutlined />}
                onClick={handleReset}
              >
                重置
              </Button>
            )}
          </Space>
        </div>

        {/* 高级筛选区域 */}
        {showAdvancedFilter && (
          <Collapse
            activeKey={showAdvanced ? ['advanced'] : []}
            ghost
            className={styles.advancedCollapse}
          >
            <Panel key="advanced" header="" showArrow={false}>
              <div className={styles.filterSection}>
                <Row gutter={[16, 16]}>
                  <Col xs={24} sm={12} md={8}>
                    <div className={styles.filterItem}>
                      <label className={styles.filterLabel}>课程分类</label>
                      <Select
                        mode="multiple"
                        value={localFilters.categoryIds}
                        onChange={(value) => handleFilterChange('categoryIds', value)}
                        placeholder="选择课程分类"
                        allowClear
                        className={styles.filterSelect}
                        maxTagCount="responsive"
                      >
                        {categories.map(category => (
                          <Option key={category.id} value={category.id}>
                            <div className={styles.categoryOption}>
                              <div 
                                className={styles.categoryColor}
                                style={{ backgroundColor: category.color }}
                              />
                              {category.name}
                            </div>
                          </Option>
                        ))}
                      </Select>
                    </div>
                  </Col>
                  
                  <Col xs={24} sm={12} md={8}>
                    <div className={styles.filterItem}>
                      <label className={styles.filterLabel}>授课教师</label>
                      <Input
                        value={localFilters.teacher}
                        onChange={(e) => handleFilterChange('teacher', e.target.value)}
                        placeholder="输入教师姓名"
                        allowClear
                      />
                    </div>
                  </Col>
                  
                  <Col xs={24} sm={12} md={8}>
                    <div className={styles.filterItem}>
                      <label className={styles.filterLabel}>状态</label>
                      <Select
                        value={localFilters.status}
                        onChange={(value) => handleFilterChange('status', value)}
                        placeholder="选择状态"
                        allowClear
                        className={styles.filterSelect}
                      >
                        <Option value={CourseStatusEnum.ACTIVE}>正常</Option>
                        <Option value={CourseStatusEnum.SUSPENDED}>暂停</Option>
                      </Select>
                    </div>
                  </Col>
                </Row>
              </div>
            </Panel>
          </Collapse>
        )}
      </Card>

      {/* 筛选条件显示 */}
      {(hasFilters || hasSearch) && (
        <div className={styles.filterTags}>
          <span className={styles.filterLabel}>当前筛选：</span>
          <Space wrap>
            {hasSearch && (
              <Tag className={styles.filterTag} closable={false}>
                关键词: "{searchKeyword}"
              </Tag>
            )}
            {getSelectedCategoryNames().map(categoryName => (
              <Tag key={categoryName} className={styles.filterTag} closable={false}>
                分类: {categoryName}
              </Tag>
            ))}
            {localFilters.teacher && (
              <Tag className={styles.filterTag} closable={false}>
                教师: {localFilters.teacher}
              </Tag>
            )}
            {localFilters.status && (
              <Tag className={styles.filterTag} closable={false}>
                状态: {localFilters.status === CourseStatusEnum.ACTIVE ? '正常' : '暂停'}
              </Tag>
            )}
          </Space>
        </div>
      )}
    </div>
  );
});

CourseSearch.displayName = 'CourseSearch';

export default CourseSearch;